import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import moment from 'moment';
import { message } from 'antd';
/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = (path) => reg.test(path);
export const isAntDesignPro = () => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }

  return window.location.hostname === 'preview.pro.ant.design';
}; // 给官方演示站点用，用于关闭真实开发环境不需要使用的特性

export const isAntDesignProOrDev = () => {
  const { NODE_ENV } = process.env;

  if (NODE_ENV === 'development') {
    return true;
  }

  return isAntDesignPro();
};
export const getPageQuery = () => parse(window.location.href.split('?')[1]);
/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */

export const getAuthorityFromRouter = (router = [], pathname) => {
  const authority = router.find(
    ({ routes, path = '/' }) =>
      (path && pathRegexp(path).exec(pathname)) ||
      (routes && getAuthorityFromRouter(routes, pathname)),
  );
  if (authority) return authority;
  return undefined;
};
// 判断路由级别的权限
export const getRouteAuth = (path, routeData) => {
  return routeData.some((route) => {
    if (route.path === path) {
      return true;
    } else if (
      route.containPath &&
      ~route.containPath.split(';').indexOf(path)
    ) {
      return true;
    } else if (route.children) {
      return getRouteAuth(path, route.children);
    } else {
      return false;
    }
  });
};
// 判断组件级别的权限
export const getComponentAuth = (code, permissions) => {
  return permissions.includes(code);
};
export const getItemWithCompare = (compare, value, data) => {
  let res = {};
  data.every((item) => {
    const compared =
      typeof compare === 'function'
        ? compare(item, value)
        : compare.every((func) => func(item, value));
    if (compared) {
      res = item;
      return false;
    } else {
      if (item?.children) {
        res = getItemWithCompare(compare, value, item?.children);
        return Object.keys(res).length === 0;
      } else {
        return true;
      }
    }
  });
  return res;
};

const PAGE_TYPE = '2';
const MENU_TYPE = '1';
export const getPageItemByPath = (path, menuData) => {
  const comparePath = (item, value) => item && item.path === value;
  const compareContainPath = (item, value) =>
    item && item.containPath && ~item.containPath.split(';').indexOf(value);
  const comparePageType = (item, _) => item && item.type == PAGE_TYPE;
  const compareMenuType = (item, _) => item && item.type == MENU_TYPE;
  const compares = (item, value) =>
    comparePath(item, value) || compareContainPath(item, value);

  const findPageItem = getItemWithCompare(
    [compares, comparePageType],
    path,
    menuData,
  );

  if (findPageItem.id) {
    return findPageItem;
  }

  const findMenuItem = getItemWithCompare(
    [compares, compareMenuType],
    path,
    menuData,
  );

  if (findMenuItem.routes && findMenuItem.routes.length > 0) {
    return getPageItemByPath(findMenuItem.routes[0].path, findMenuItem.routes);
  }

  return {};
};

export const getPageItemById = (id, menuData) => {
  const compareId = (item, value) => item && item.id === value;
  return getItemWithCompare(compareId, id, menuData);
};

export const getParentMenuByPage = (page, menuData) => {
  const compareId = (item, value) => item && item.id === value;
  return getItemWithCompare(compareId, page.pid, menuData);
};

// < 3h : n小时前 / n分钟前
// >= 3h < 1d : hh:mm
// >1d < 2d : 昨天
// < 1y : mm-dd hh:mm
// >= 1y : yyyy-mm-dd
export const formatMoment = function formatMoment(date) {
  const yearEq = moment(date).year() === moment().year();
  const dayEq = moment(date).dayOfYear() === moment().dayOfYear();
  const dayAgoEq =
    moment(date).format('YYYYMMDD') ===
    moment().subtract(1, 'd').format('YYYYMMDD');
  const hour3Ago = moment(date).add(3, 'h').valueOf() > Date.now();

  switch (true) {
    case hour3Ago:
      return moment(date).fromNow();
    case yearEq && dayEq:
      return moment(date).format('HH:mm');
    case dayAgoEq:
      return moment(date).format('[昨天] HH:mm');
    case yearEq:
      return moment(date).format('MM[月] DD[日] HH:mm');
    default:
      return moment(date).format('YYYY[年] MM[月] DD[日]');
  }
};

export const phoneNumFormat = function phoneNumFormat(num) {
  if (!num) {
    return '';
  }
  return ''.replace
    .call(num, /^([0-9]{3})([^\s]+)$/, '$1 $2')
    .replace(/([0-9]{4})(?=[0-9])/g, '$1 ');
};

/**
 * 根据秒数返回（天，小时，分钟，秒），秒以上的时间为空，则不展示该时间段
 * 示例：1天2时3分4秒，5分6秒
 */
export const intervalTime = ($time) => {
  //计算天
  let $days = $time >= 86400 ? Math.floor($time / 86400) : 0;
  //计算小时
  var $temp = $time - 86400 * $days;
  let $hour = $temp >= 3600 && $temp < 86400 ? Math.floor($temp / 3600) : 0;
  //计算分钟
  $temp = $time - 86400 * $days - 3600 * $hour;
  let $minute = $temp >= 60 && $temp < 3600 ? Math.floor($temp / 60) : 0;
  //计算秒
  $temp = $time - 86400 * $days - 3600 * $hour - 60 * $minute;
  let $second = $temp > 0 && $temp < 60 ? $temp : 0;
  // let $result = `${$days ? `${$days}天` : ''}
  //   ${$hour ? `${$hour}时` : ''}
  //   ${$minute ? `${$minute}分` : ''}
  //   ${$second}秒`
  let $result = `${$days}天 ${$hour}时 ${$minute}分 ${$second}秒`;
  return $result;
};
// 过滤菜单树 提取type===3 的权限 并且排除type == 3 的权限列表
// 任总看到别骂我
export const filterMenuTree = (resourceArr) => {
  for (const item of resourceArr) {
    item.path = item.routeUrl;
    item.id = String(item.id);
    // 提取
    if (item?.type == 2 &&
      item?.children &&
      item?.children[0]?.type == 2 &&
      item?.children[0]?.children &&
      item?.children[0]?.children[0]?.type == 3) {
      for (const menuChild of item?.children) {
        if (menuChild?.children && menuChild?.children[0]?.type == 3) {
          for (const operateChild of menuChild?.children) {
            if (operateChild.routeUrl) {
              operateChild.hideInMenu = true;
              // operateChild.type = 2;
              item.children.push(operateChild);
            }
          }
        }

      }
    };
    // 过滤
    if (item.type == 2 && item.children) {
      if (item?.children[0]?.type == 3) {
        item.children = null;
      } else {
        filterMenuTree(item.children);
      }
    }
  }
  return resourceArr;
}


export function formatTreeData(data) {
  let parentIds = new Set();
  let soniDs = new Set();
  function _formatAndGetIds(data) {
    if (Array.isArray(data) && data.length > 0) {
      for (const item of data) {
        item.type = String(item.type);
        item.path = item.routeUrl;
        item.hideInMenu = false;
        if (item.type === "3" && item.path) {
          item.hideInMenu = true;
          parentIds.add(item.parentId);
          soniDs.add(item.id);
        }
        if (item.children && item.children.length > 0) {
          _formatAndGetIds(item.children);
        }
      }
    }
  }
  _formatAndGetIds(data);
  function _lastFormat(data) {
    if (Array.isArray(data) && data.length > 0) {
      for (const item of data) {
        if (parentIds.has(item.id)) {//代表他是有子集的
          for (const item2 of item.children) {
            if (soniDs.has(item2.id)) {
              data.push(item2)
            }
          }
        }
        if (item.children && item.children.length > 0) {
          _lastFormat(item.children);
        }
      }
    }
  }
  _lastFormat(data);
  return data;
}